package ${projectRootPackage}.configuration;

import ldh.oauth.base.AuthorityTokenServices;
import net.sf.ehcache.CacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.security.oauth2.client.OAuth2SsoProperties;
import org.springframework.boot.autoconfigure.security.oauth2.resource.ResourceServerProperties;
import org.springframework.boot.autoconfigure.security.oauth2.resource.UserInfoTokenServices;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.oauth2.client.OAuth2ClientContext;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.security.oauth2.client.filter.OAuth2ClientAuthenticationProcessingFilter;
import org.springframework.security.oauth2.client.resource.OAuth2ProtectedResourceDetails;
import org.springframework.security.oauth2.provider.token.ResourceServerTokenServices;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.web.authentication.SimpleUrlAuthenticationSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Configuration
public class OAuth2ClientConfig {

    @Resource
    private ResourceServerProperties resourceServerProperties;
    @Resource
    private OAuth2ProtectedResourceDetails oAuth2ProtectedResourceDetails;
    @Autowired
    public OAuth2ClientContext oAuth2ClientContext;
    @Resource
    private TokenStore tokenStore;
    @Autowired
    private CacheManager cacheManager;

    @Bean("oAuth2RestTemplate")
    public OAuth2RestTemplate restOperations() {
        return new OAuth2RestTemplate(oAuth2ProtectedResourceDetails, oAuth2ClientContext);
    }

    @Bean
    public OAuth2ClientAuthenticationProcessingFilter oauth2ClientAuthenticationProcessingFilter(
            OAuth2RestTemplate oauth2RestTemplate,
            ResourceServerTokenServices tokenService, OAuth2SsoProperties oAuth2SsoProperties) {
        OAuth2ClientAuthenticationProcessingFilter filter = new OAuth2ClientAuthenticationProcessingFilter(oAuth2SsoProperties.getLoginPath());
        filter.setRestTemplate(oauth2RestTemplate);
        filter.setTokenServices(tokenService);

        return filter;
    }

    @Bean
    public ResourceServerTokenServices tokenService() {
        AuthorityTokenServices tokenService = new AuthorityTokenServices(resourceServerProperties, cacheManager);
        tokenService.setTokenStore(tokenStore);
//        UserInfoTokenServices tokenService = new UserInfoTokenServices(resourceServerProperties.getUserInfoUri(), resourceServerProperties.getClientId());
        return tokenService;
    }
}
